#pragma once

#include<iostream>
#include<queue>
#include<pthread.h>


template <typename T>
class BlockQueue
{
public:
    BlockQueue()
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_fillcond,nullptr);
        pthread_cond_init(&_emptycond,nullptr);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_fillcond);
        pthread_cond_destroy(&_emptycond);
    }

    bool IsFill()
    {
        return  _q.size() == _capacity; 
    }

    bool IsEmpty()
    {
        return _q.empty();
    }

    void EnterQueue(const T& data)
    {
        pthread_mutex_lock(&_mutex);
        while(IsFill()) //防止伪唤醒
        {
            ++_psleepnum;
            pthread_cond_wait(&_fillcond,&_mutex);
            --_psleepnum;
        }
        //入队列
        _q.push(data);   
        if(_csleepnum > 0)
        {
            //唤醒消费者
            std::cout << "唤醒消费者" <<std::endl;
            pthread_cond_signal(&_emptycond);
        }
        pthread_mutex_unlock(&_mutex);
    }

    T PopQueue()
    {
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            ++_csleepnum;
            pthread_cond_wait(&_emptycond,&_mutex);
            --_csleepnum;
        }
        T data = _q.front();
        _q.pop();
        if(_psleepnum > 0)
        {
            std::cout << "唤醒生产者" << std::endl;
            pthread_cond_signal(&_fillcond);
        }
        pthread_mutex_unlock(&_mutex);
        return data;
    } 


private:
    std::queue<T> _q;
    int _capacity = 5;
    pthread_mutex_t _mutex;
    pthread_cond_t _fillcond;
    pthread_cond_t _emptycond;
    int _psleepnum = 0;
    int _csleepnum = 0;
};
